package Client;

import java.awt.*;
import java.awt.image.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class Smiley implements CaretListener {

	protected ImageIcon getImage() {
		BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
		Graphics g = bi.getGraphics();
		g.setColor(Color.red);
		g.drawOval(0, 0, 14, 14);
		g.drawLine(4, 9, 9, 9);
		g.drawOval(4, 4, 1, 1);
		g.drawOval(10, 4, 1, 1);
		return new ImageIcon(bi);
	}

	@Override
	public void caretUpdate(CaretEvent e) {
		SimpleAttributeSet attrs = new SimpleAttributeSet();
		StyleConstants.setIcon(attrs, getImage());

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					StyledDocument doc = (StyledDocument) Client_Gui.inputTextArea.getDocument();
					String text = doc.getText(0, Client_Gui.inputTextArea.getDocument().getLength());
					int index = text.indexOf(":)");
					int start = 0;
					while (index > -1) {
						Element el = doc.getCharacterElement(index);
						if (StyleConstants.getIcon(el.getAttributes()) == null) {
							doc.remove(index, 2);
							SimpleAttributeSet attrs = new SimpleAttributeSet();
							StyleConstants.setIcon(attrs, getImage());
							doc.insertString(index, ":)", attrs);
						}
						start = index + 2;
						index = text.indexOf(":)", start);
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
	}

}